/**
 * 
 */
package ch.baeni.jee.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

/**
 * URL-Validator Klasse
 * 
 * @author Benjamin
 * 
 */
@FacesValidator("CustomUrlValidator")
public class CustomUrlValidator implements Validator {

	private static final String URL_PATTERN_WITH_PREFIX = "((https?|ftp|file)://)?([-;:&=\\+\\$,\\w]+@{1})?(([-A-Za-z0-9]+\\.)+[A-Za-z]{2,3})(:\\d+)?((/[-\\+~%/\\.\\w]+)?/?([&?][-\\+=&;%@\\.\\w]+)?(#[\\w]+)?)?";
	private static final String HTTP = "http://";

	private Pattern patternWithPrefix;
	private Matcher matcher;

	/**
	 * Default-Constructor
	 */
	public CustomUrlValidator() {
		patternWithPrefix = Pattern.compile(URL_PATTERN_WITH_PREFIX);
	}

	/**
	 * URL validieren
	 * 
	 * @see javax.faces.validator.Validator#validate(javax.faces.context.FacesContext
	 *      , javax.faces.component.UIComponent, java.lang.Object)
	 */
	@Override
	public void validate(FacesContext context, UIComponent component,
			Object value) throws ValidatorException {
		String url = value.toString();
		matcher = patternWithPrefix.matcher(url);
		if (!matcher.matches()) {
			matcher = patternWithPrefix.matcher(HTTP + url);
			if (!matcher.matches()) {
				FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR,
						"No valid URL", "Validation Error");
				throw new ValidatorException(m);
			}
		}
	}

}
